package com.demo.search.context.impl;

import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.IndexSearcher;

import com.demo.search.context.IndexContext;
import com.demo.search.engine.SearchEngine;

/**
 * 索引管理器实现类
 * @author ryuu.kk
 *
 */
public class LocalIndexContext implements IndexContext {

	/**
	 * 写入索引对象
	 */
	private IndexWriter indexWriter;
	
	/**
	 * 读取索引对象
	 */
	private IndexReader indexReader;
	
	/**
	 * 模型-Document双向转换引擎
	 */
	private SearchEngine engine;
	
	/**
	 * 构造函数
	 * @param indexWriter
	 */
	public LocalIndexContext(SearchEngine engine) {
		this.engine = engine;
		this.indexWriter = engine.ownerIndexWriter();
	}
	
//	/**
//	 * 构造函数
//	 * @param indexPath 索引所在位置
//	 * @param writerConfig IndexWriterConfig
//	 * @throws IOException IO异常
//	 */
//	public LocalIndexContext(String indexPath, IndexWriterConfig writerConfig) throws IOException {
//		Directory directory = LuceneUtils.createFSDriectory(indexPath);
//		indexWriter = new IndexWriter(directory, writerConfig);
//	}
	
	@Override
	public IndexReader getIndexReader() {
		IndexReader newReader = null;
		if (indexReader == null) {
			return createIndexReader();
		}
		try {
			// 索引快照
			newReader = IndexReader.openIfChanged(indexReader);
			if (newReader != null) {
				indexReader.close();
				indexReader = newReader;
			}
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e.getCause());
		}
		return this.indexReader;
	}

	@Override
	public IndexReader createIndexReader() {
		try {
			indexReader = IndexReader.open(indexWriter, true);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e.getCause());
		} 
		return indexReader;
	}

	@Override
	public IndexWriter getIndexWriter() {
		return this.indexWriter;
	}

	@Override
	public IndexSearcher Sesarchbuilder() {
		return new IndexSearcher(getIndexReader());
	}
	
	@Override
	public SearchEngine getEngine() {
		return this.engine;
	}
}
